package org.jenijo.querydroid;

import java.io.UnsupportedEncodingException;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements View.OnClickListener, OnKeyListener {
	
	Button						connect, reset;
	EditText					login, password;
	AutoCompleteTextView		server;
	String						filteredLogin, filteredPassword, filteredServer;
	
	ProgressBar					prog;
	
	AsyncTask<Void, Void, Void>	t;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		setContentView(R.layout.login);
		
		ServerErrorHandler.ctx = this;
		
		new DeviceUuidFactory(this).getDeviceUuid();
		
		connect = (Button) findViewById(R.id.butConnect);
		reset = (Button) findViewById(R.id.butReset);
		login = (EditText) findViewById(R.id.etLogin);
		password = (EditText) findViewById(R.id.etPassword);
		server = (AutoCompleteTextView) findViewById(R.id.etServer);
		prog = (ProgressBar) findViewById(R.id.progressBar1);
		
		SharedPreferences pref = getSharedPreferences("QDServerList", 0);
		String servList = pref.getString("ServerList", null);
		if(servList != null){
			String[] servTab = servList.split(";");
			ArrayAdapter<String> adap = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, servTab);
			server.setThreshold(1);
			server.setOnKeyListener(this);
			server.setAdapter(adap);
		}
		connect.setOnClickListener(this);
		reset.setOnClickListener(this);
	}
	
	public void onClick(View v) {
		switch(v.getId()) {
			case R.id.butConnect:
				connectAction();
				break;
			case R.id.butReset:
				resetAction();
				break;
		}
	}
	
	private void connectAction() {
		filteredLogin = this.login.getText().toString().trim().toLowerCase();
		filteredPassword = this.password.getText().toString().trim().toLowerCase();
		filteredServer = this.server.getText().toString().trim().toLowerCase();
		
		if(filteredLogin.equals("") || filteredPassword.equals("")){
			Toast.makeText(this, R.string.emptyFieldError, Toast.LENGTH_SHORT).show();
		}else if(!this.isConnected()){
			new AlertDialog.Builder(this).setTitle(R.string.error).setMessage(R.string.notConnectedError).setPositiveButton(R.string.okButton, null).show();
		}else{
			if(filteredServer.equals(""))
				filteredServer = getString(R.string.masterServer);
			final String url = "http://" + filteredServer + "/android/login";
			
			t = new AsyncTask<Void, Void, Void>() {
				RestClient	client;
				
				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					prog.setVisibility(View.VISIBLE);
					client = new RestClient(url);
					client.addParam("login", filteredLogin).addParam("password", filteredPassword);
				}
				
				@Override
				protected Void doInBackground(Void... params) {
					try{
						client.execute(RequestMethod.POST);
					}catch (UnsupportedEncodingException e){
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return null;
				}
				
				@Override
				protected void onPostExecute(Void data) {
					super.onPostExecute(data);
					String type;
					prog.setVisibility(View.INVISIBLE);
					if(client.getResponse() != null){
						try{
							JSONObject result = new JSONObject(client.getResponse());
							type = (String) result.get("type");
							if(type.equals("loginSuccess")){
								Intent i = new Intent(LoginActivity.this, MainActivity.class);
								i.putExtra("server", filteredServer);
								i.putExtra("login", filteredLogin);
								i.putExtra("password", filteredPassword);
								LoginActivity.this.startActivity(i);
								LoginActivity.this.finish();
							}else{
								if(type.equals("loginFailed")){
									new AlertDialog.Builder(LoginActivity.this).setTitle(R.string.error).setMessage(R.string.wrongLoginPassError).setPositiveButton(R.string.okButton, null).show();
								}else if(type.equals("invalidLoginForm")){
									new AlertDialog.Builder(LoginActivity.this).setTitle(R.string.error).setMessage(R.string.invalidFormError).setPositiveButton(R.string.okButton, null).show();
								}
							}
						}catch (Exception e){
							new AlertDialog.Builder(LoginActivity.this).setTitle(R.string.error).setMessage(client.getResponse()).setPositiveButton(R.string.okButton, null).show();
						}
					}else
						new AlertDialog.Builder(LoginActivity.this).setTitle(R.string.error).setMessage(client.getErrorMessage()).setPositiveButton(R.string.okButton, null).show();
				}
			}.execute();
		}
	}
	
	private void resetAction() {
		login.setText("");
		password.setText("");
		server.setText("");
		prog.setVisibility(View.INVISIBLE);
		try{
			t.cancel(true);
			t = null;
		}catch (Exception e){
			e = null;
		}
	}
	
	private boolean isConnected() {
		ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = null;
		if(connectivityManager != null){
			networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if(networkInfo == null){
				networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			}
		}
		if(networkInfo == null)
			return false;
		else
			return networkInfo.isConnected();
	}
	
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_ENTER){
			server.dismissDropDown();
			server.setInputType(InputType.TYPE_NULL);
			server.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
		}
		return false;
	}
}